package ua.exchangeratesukraine.ui.fragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;

import ua.exchangeratesukraine.R;
import ua.exchangeratesukraine.model.CurrencyModel;
import ua.exchangeratesukraine.ui.activity.DBHelper;
import ua.exchangeratesukraine.util.Constants;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;

public class FragmentBase extends SherlockListFragment implements OnClickListener, SetDataListener, OnTouchListener,
		OnItemSelectedListener {

	protected String					LOG_TAG				= getClass().getSimpleName();
	protected Context					context				= null;
	protected TextView					tvCurrentDate		= null;
	protected TextView					tvSetBank			= null;
	protected Button					btnResult			= null;
	protected View						listHeader			= null;
	protected View						listFooter			= null;
	protected TextView					tvDate				= null;
	protected ProgressBar				bar					= null;
	protected BaseAdapter				adapter				= null;
	protected String					BASE_URL			= Constants.BASE_URL;
	protected String					WEB_ID				= Constants.WEB_ID;
	protected boolean					isListShow			= false;
	protected boolean					isDialogShow		= false;
	protected boolean					isNetworkAvailable	= false;
	protected String					date				= "";
	protected ArrayList<CurrencyModel>	currencyModelArray	= new ArrayList<CurrencyModel>();
	protected ArrayList<String>			holidayMonthArray	= new ArrayList<String>();
	protected ArrayList<String>			holidayDayArray		= new ArrayList<String>();
	protected HashMap<String, String>	currency			= new HashMap<String, String>();

	protected int						touchUnitCount		= 0;
	protected int						touchChangeCount	= 0;
	protected int						touchAbsCount		= 0;
	protected int						touchRelCount		= 0;

	protected int						touchBuyCount		= 0;
	protected int						touchAbsBuyCount	= 0;
	protected int						touchAbsSaleCount	= 0;
	protected int						touchSaleCount		= 0;
	protected int						touchRelBuyCount	= 0;
	protected int						touchRelSaleCount	= 0;

	protected DBHelper					dbHelper			= null;
	protected ContentValues				cv					= null; // create object for data
	protected SQLiteDatabase			db					= null; // connect to DB

	@Override
	public void onCreate(Bundle inState) {

		context = getSherlockActivity();
		holidayMonthArray = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.holiday_month)));
		holidayDayArray = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.holiday_day)));
		super.onCreate(inState);
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
	}

	protected void fillTvCurrentDate(String date) {
		tvCurrentDate.setText(date);
	}

	protected void fillTvDate(String date) {
		tvDate.setText(date);
	}

	protected String getCurrentDate() {
		Calendar sDate = Calendar.getInstance();
		Log.d(LOG_TAG, "YEAR = " + sDate.get(Calendar.YEAR) + "; MONTH = " + (sDate.get(Calendar.MONTH) + 1)
				+ "; DAY_OF_MONTH = " + (sDate.get(Calendar.DAY_OF_MONTH)));
		return ""
				+ sDate.get(Calendar.YEAR)
				+ "-"
				+ (((sDate.get(Calendar.MONTH) + 1) > 9) ? (sDate.get(Calendar.MONTH) + 1) : (("0"
						+ (sDate.get(Calendar.MONTH) + 1))))
						+ "-"
						+ ((sDate.get(Calendar.DAY_OF_MONTH) > 9) ? sDate.get(Calendar.DAY_OF_MONTH) : ("0" + sDate
								.get(Calendar.DAY_OF_MONTH))); 

	}

	protected void showDateDialog() {
		DateDialogFragment datePicker = DateDialogFragment.newInstance(getActivity());
		datePicker.setDateDialogFragmentListener(new DateDialogFragmentListener() {
			@Override
			public void dateDialogFragmentDateSet(int year, int monthOfYear, int dayOfMonth) {
				int month = monthOfYear + 1;
				date = year + "-" + ((month > 9) ? month : ("0" + month)) + "-"
						+ ((dayOfMonth > 9) ? dayOfMonth : ("0" + dayOfMonth));
				fillTvCurrentDate(date);
			}
		});
		datePicker.show(getActivity().getSupportFragmentManager(), "date picker dialog fragment");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setData(Object result, Bundle inState) {
		String connectionError = getString(R.string.text_toast_connection_error);
		String urlConnectionError = getString(R.string.text_toast_url_connection_error);
		String requests_limit = "requests_limit";
		if ((result.toString()).equals(connectionError)) {
			showToast(getString(R.string.title_toast_connection_error), connectionError);
			return;
		} else if ((result.toString()).equals(urlConnectionError)) {
			showToast(getString(R.string.title_toast_connection_error), urlConnectionError);
			return;
		} else if ((result.toString()).equals(requests_limit)) {
			showToast(getString(R.string.title_toast_url_connection_error), urlConnectionError);
			return;
		}
		currencyModelArray = (ArrayList<CurrencyModel>) result;
		Log.d(LOG_TAG, "Array size = " + currencyModelArray.size());

		// for (CurrencyModel currencyModel : currencyModelArray) {
		// Log.d(LOG_TAG, "Bank CODE = " + currencyModel.getCode() + " - " + currencyModel.getName());
		// Log.d(LOG_TAG, "Date----------> = " + currencyModel.getDate());
		// }

		if (currencyModelArray.isEmpty()) {
			showToast(getString(R.string.title_toast_attention), getString(R.string.text_array_empty_date));
			return;
		}
		if (!isListShow) {
			setListAdapter(null);
			setListHeader(listHeader);
			getListView().addFooterView(listFooter);
		}
		setCurrencyName(currencyModelArray); // for NBU
		if (!Locale.getDefault().toString().equals("ru_RU"))
			setBanksName(currencyModelArray); // for Banks

//		writeDataToDB();
		
		sort((TextView) getActivity().findViewById(R.id.tvNameCurrencyUnit), true);
		initArray(currencyModelArray);
	}
	
	protected void setDataFromDB() {
	}

	protected void writeDataToDB() {
	}

	protected void setCurrencyName(ArrayList<CurrencyModel> currencyModelArray) {
	}

	protected void setBanksName(ArrayList<CurrencyModel> currencyModelArray) {
	}

	protected void initArray(ArrayList<CurrencyModel> currencyModelArray) {
		this.currencyModelArray = currencyModelArray;
		for (CurrencyModel currencyModel : currencyModelArray) {
			Log.d(LOG_TAG, "Display currencyModel = " + currencyModel.getName());
		}
		adapter = getAdapter();
		setListAdapter(adapter);
		adapter.notifyDataSetChanged();
		fillTvDate(" " + getString(R.string.text_on_date) + " " + date);
		isListShow = true;
	}

	protected BaseAdapter getAdapter() {
		return null;
	}

	public void setListHeader(View listHeader) {
		getListView().addHeaderView(listHeader);
	}

	@Override
	public void setProgressVisible() {
		bar.setVisibility(View.VISIBLE);
	}

	@Override
	public void setProgressInVisible() {
		bar.setVisibility(View.INVISIBLE);
	}

	@Override
	public boolean onTouch(View v, MotionEvent motionEvent) {
		switch (motionEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (v.getId() == R.id.btnResult) {
					btnResult.setBackgroundResource(R.drawable.button_nbu_pressed);
					btnResult.setTextColor(Color.WHITE);
				}
				if (v.getId() == R.id.tvSetBank) {
					tvSetBank.setBackgroundResource(R.drawable.tv_current_date_pressed);
					tvSetBank.setTextColor(Color.WHITE);
				}
				if (v.getId() == R.id.tvCurrentDate) {
					tvCurrentDate.setBackgroundResource(R.drawable.tv_current_date_pressed);
					tvCurrentDate.setTextColor(Color.WHITE);
				}
				break;
			case MotionEvent.ACTION_CANCEL:
			case MotionEvent.ACTION_UP:
				if (v.getId() == R.id.btnResult) {
					btnResult.setBackgroundResource(R.drawable.button_nbu_normal);
					btnResult.setTextColor(Color.DKGRAY);
				}
				if (v.getId() == R.id.tvSetBank) {
					tvSetBank.setBackgroundResource(R.drawable.tv_current_date_normal);
					tvSetBank.setTextColor(Color.DKGRAY);
				}
				if (v.getId() == R.id.tvCurrentDate) {
					tvCurrentDate.setBackgroundResource(R.drawable.tv_current_date_normal);
					tvCurrentDate.setTextColor(Color.DKGRAY);
				}
				break;
		}
		return false;
	}

	protected void showToast(String title, String message) {
		LayoutInflater inflater = getLayoutInflater(null);
		View layoutToast = inflater.inflate(R.layout.toast, (ViewGroup) getView().findViewById(R.id.layoutToast));
		TextView tvTitleToast = (TextView) layoutToast.findViewById(R.id.tvTitleToast);
		tvTitleToast.setText(title);
		TextView tvTextToast = (TextView) layoutToast.findViewById(R.id.tvTextToast);
		tvTextToast.setText(message);

		Toast toast = new Toast(context);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(layoutToast);
		toast.show();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		setListAdapter(null);
	}

	public ArrayList<CurrencyModel> getCurrencyModelArray() {
		return currencyModelArray;
	}

	public void sort(View view, boolean isFirstRequest2) {
	}

	@Override
	public void onClick(View view) {
	}

}